import {ActionType, PageContainer, ProColumns, ProTable} from '@ant-design/pro-components';
import {FormattedMessage} from '@umijs/max';
import {message, Tag, Tooltip} from 'antd';
import React, {useRef, useState, useEffect} from 'react';
import {userList, assignUserRoles} from '@/services/users/api';
import {useNavigate, useLocation} from "react-router-dom";


const UserTableList: React.FC = () => {
  const actionRef = useRef<ActionType | null>(null);
  const [messageApi, contextHolder] = message.useMessage();
  const navigate = useNavigate();
  const location = useLocation();


  const getJumpInfo = () => {
    const stepData = location.state as JumpData<API.AssignRolesReq>;
    if (stepData) {
      const {flag, data} = stepData;
      return {flag, data};
    }
    return null;
  }

  // 处理从角色权限页面返回的数据
  useEffect(() => {
    let jumpFromData = getJumpInfo();
    if (jumpFromData) {
      switch (jumpFromData.flag) {
        case 'rolesPermission':
          console.log('从用户列表页面过来，数据已处理');
          console.log('从用户列表页面过来，数据是：', jumpFromData.data);
          if (jumpFromData.data.userId && jumpFromData.data.roleIds && jumpFromData.data.roleIds.length>0){
            let userId = jumpFromData.data.userId;
            let roleIds = jumpFromData.data.roleIds;
            console.log('角色分配数据:', {userId, roleIds});
            //角色分配
            handleRoleAssignment(userId, roleIds);
            window.history.replaceState(null, '', window.location.pathname);
          }
          break;
        default:
          console.log('从其他页面过来');
      }
    }
  }, [location.state]);

  // 处理角色分配
  const handleRoleAssignment = async (userId: number, roleIds: number[]) => {
    try {
      await assignUserRoles(userId, roleIds);
      messageApi.success('角色分配成功');
      // 刷新用户列表
      actionRef.current?.reload();
    } catch (error: any) {
      console.error('分配角色失败:', error);
      messageApi.error(error.data?.message || '分配角色失败，请重试');
    }
  };

  const fetchUserList = async (params: any, sort: any, filter: any) => {
    try {
      const result = await userList(params, sort, filter);
      return {
        ...result,
        success: true,
      };
    } catch (error: any) {
      console.error('ProTable request error:', error);
      messageApi.error(error.data?.message || '列表加载失败，请重试');
      return {
        data: [],
        success: false,
        total: 0,
      };
    }
  };

  const columns: ProColumns<API.UserListItem>[] = [
    {
      title: 'ID',
      dataIndex: 'id',
      width: '8%',
      hideInSearch: true,
      render: (_, record) => record.userInfo.id,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      width: '15%',
      fieldProps: {
        style: {
          width: 160,
        },
      },
      render: (_, record) => record.userInfo.username,
    },
    {
      title: '角色',
      dataIndex: 'role',
      width: '20%',
      fieldProps: {
        style: {
          width: 160,
        },
      },
      render: (_, record) => (
        <>
          {record.userRoles.map((role) => (
            <Tooltip title={role.description} key={role.id}>
              <Tag color="blue">{role.name}</Tag>
            </Tooltip>
          ))}
        </>
      ),
    },
    {
      title: (
        <FormattedMessage
          id="pages.switch-meta.searchTable.createTime"
          defaultMessage="创建时间"
        />
      ),
      sorter: true,
      hideInForm: true,
      width: '20%',
      dataIndex: 'createTime',
      key: 'updatedAt',
      valueType: 'dateTimeRange',
      fieldProps: {
        style: {
          width: 320,
        },
      },
      render: (_, record) => {
        if (!record.userInfo.createTime) return '-';
        return record.userInfo.createTime.replace('T', ' ').substring(0, 19);
      },
    },
    {
      title: '更新时间',
      sorter: true,
      width: '20%',
      hideInSearch: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      render: (_, record) => {
        if (!record.userInfo.updateTime) return '-';
        return record.userInfo.updateTime.replace('T', ' ').substring(0, 19);
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.system.titleOption"
          defaultMessage="操作"
        />
      ),
      dataIndex: 'option',
      valueType: 'option',
      width: '12%',
      render: (_, record) => [
        <a
          key="edit"
          onClick={async (e) => {
            e.preventDefault();

            try {
              const jumpData: JumpData = {
                flag: 'users',
                data: {
                  userId: record.userInfo.id,
                }
              };
              console.log('准备跳转，携带数据:', jumpData);
              navigate('/user-center/roles-permission', {state: jumpData});
            } catch (error) {
              messageApi.error('操作失败，请重试');
            }
          }}
          style={{cursor: 'pointer'}}
        >
          <FormattedMessage
            id="pages.namespace.searchTable.bindEnvs1"
            defaultMessage="分配角色"
          />
        </a>
      ],
    },
  ];

  return (
    <PageContainer>
      {contextHolder}
      <ProTable<API.UserListItem, API.PageParams>
        headerTitle='用户列表'
        actionRef={actionRef}
        rowKey={(record) => record.userInfo.id}
        search={{
          labelWidth: 'auto',
          span: {
            xs: 24,
            sm: 12,
            md: 8,
            lg: 8,
            xl: 6,
            xxl: 6,
          },
        }}
        request={fetchUserList}
        columns={columns}
      />
    </PageContainer>
  );
};

export default UserTableList;
